package br.com.tarlis.persistent.server.mysql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import br.com.tarlis.core.server.exception.UnexpectedException;
import br.com.tarlis.persistent.server.DatabaseConnection;

public class MySQLDatabaseConnection extends DatabaseConnection<Connection> {

	/** 
	 * Creates a new MySQL connection.
	 * 
	 * @param params Expect this 3 parameters:
	 * - params[0] => URL
	 * - params[1] => USER
	 * - params[2] => PASSWORD
	 * 
	 * @return The MySQL Connection.
	 */
	@Override
	public void connect(String... params) {
		
		try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();

            setConnection(DriverManager.getConnection(
            		params[0], params[1], params[2]));

        } catch (SQLException ex) {
            ex.printStackTrace();
            throw new UnexpectedException(ex);
        } catch (InstantiationException ex) {
            ex.printStackTrace();
            throw new UnexpectedException(ex);
        } catch (IllegalAccessException ex) {
            ex.printStackTrace();
            throw new UnexpectedException(ex);
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
            throw new UnexpectedException(ex);
        }
	}

	@Override
	public void close() {
		try {
			getConnection().close();
		} catch (SQLException ex) {
			ex.printStackTrace();
            throw new UnexpectedException(ex);
		}
	}
	
	@Override
	public void commit() {
		try {
			getConnection().commit();
		} catch (SQLException ex) {
			ex.printStackTrace();
            throw new UnexpectedException(ex);
		}
	}
	
	@Override
	public void rollback() {
		try {
			getConnection().rollback();
		} catch (SQLException ex) {
			ex.printStackTrace();
            throw new UnexpectedException(ex);
		}
	}

}
